package com.atguigu.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;


@Component
public class LoadBalanceImpl implements LoadBalancer {

    private AtomicInteger counter = new AtomicInteger(0);

    @Override
    public ServiceInstance getServiceInstance(List<ServiceInstance> list) {
        int i = incrementAndGetModulo(list.size());
        ServiceInstance serviceInstance = list.get(i);
        return serviceInstance;
    }

    //负载算法 返回下标
    public int incrementAndGetModulo(int modulo){
        for (;;){
            //获取当前点击量
            int current = counter.get();
            int next = (current + 1) % modulo;
            if (counter.compareAndSet(current,current+1)){
                return next % modulo;
            }
            return 0;
        }
    }
}
